import Peer, { DataConnection } from 'peerjs';

/**
 * Класс для работы с WebRTC.
 */
export class WebRTC {
  // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
  connection: DataConnection | undefined;

  get apeer() {
    return this.peer;
  }

  constructor(
    private peer = new Peer({ host: 'localhost', port: 9000, debug: 2 }),
  ) {
    console.log('Hello, WebRTC!', this.peer);

    this.peer.on('connection', (conn) => {
      console.log('>>>>>CONNECTION', conn.connectionId);
      conn.on('data', (data) => {
        console.log('Received', data);
      });

      conn.on('open', () => {
        conn.send({
          type: 'newPlayers',
        });
      });

      conn.on('error', (error) => {
        console.error('connection:error> ' + error);
      });
    });
  }

  connect(id: string) {
    this.connection = this.peer.connect(id);

    this.connection.on('data', (data) => {
      console.log('Received', data);
    });
  }

  disconnect() {
    this.connection?.close();
    this.connection = undefined;
  }

  send(data: any) {
    console.log('>>>>', data);
    this.connection?.send(data);
  }
}
